package com.quectel.cms.controller.forum;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.business.common.mobileuser.MobileUserMsgBusiness;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.business.contentaudit.ValidatorChain;
import com.quectel.business.contentaudit.ValidatorContext;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.interceptor.LoginUserSession;
import com.quectel.cms.util.SessionHolder;
import com.quectel.cms.vo.forum.ForumAuditReq;
import com.quectel.constant.PushConstants;
import com.quectel.constant.core.forum.ForumConstants;
import com.quectel.constant.core.mobileuser.MobileUserMsgConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.forum.dto.mongo.ForumPostDto;
import com.quectel.core.module.forum.service.mongo.ForumPostService;
import com.quectel.core.module.mobileuser.dto.MobileUserDto;
import com.quectel.core.module.mobileuser.service.MobileUserService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/05/10 11:21
 */
@RestController
@RequestMapping("forumPost")
@Tag(name = "ForumPostController", description = "邻友圈帖子相关api")
public class ForumPostController extends BaseController {

    @DubboReference
    private ForumPostService forumPostService;
    @DubboReference
    private VillageService villageService;
    @DubboReference
    private MobileUserService mobileUserService;

    @Autowired
    private ValidatorChain validatorChain;

    @Autowired
    private MobileUserMsgBusiness mobileUserMsgBusiness;

    /**
     * 帖子列表
     *
     * @param
     * @return
     */

    @GetMapping("auditList")
    @RequirePermissions(values = "forumPost:list")
    @Operation(summary = "帖子列表查询")
    public Response<Page<ForumPostDto>> auditList(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "查询范围1小区2城市3全国,当范围是1时传villageId,2时传cityCode")
            @RequestParam(required = false) Byte queryRange,
            @Parameter(description = "小区Id") @RequestParam(required = false) Long villageId,
            @Parameter(description = "城市code") @RequestParam(required = false) String cityCode,
            @Parameter(description = "类别,默认没有类别") @RequestParam(required = false) Byte type,
            @Parameter(description = "话题Id") @RequestParam(required = false) Long topicId,
            @Parameter(description = "查询content") @RequestParam(required = false) String queryContent,
            @Parameter(description = "发帖人手机号") @RequestParam(required = false) String mobile,
            @Parameter(description = "发帖开始时间") @RequestParam(required = false) String startTime,
            @Parameter(description = "发帖结束时间") @RequestParam(required = false) String endTime

    ) {
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        if (queryRange == null) {
            queryRange = 3;
        }

        if (queryRange == 1) {
            request.put(LambdaUtil.getFieldName(ForumPostDto::getVillageId), villageId);
        } else if (queryRange == 2) {
            request.put(LambdaUtil.getFieldName(ForumPostDto::getCityCode), cityCode);
            request.put(LambdaUtil.getFieldName(ForumPostDto::getTopFlag), SystemConstants.NO);
        } else if (queryRange == 3) {
            request.put(LambdaUtil.getFieldName(ForumPostDto::getTenantId), SessionHolder.getSysUser().getTenantId());
            request.put(LambdaUtil.getFieldName(ForumPostDto::getTopFlag), SystemConstants.NO);
        }

        if (type != null) {
            request.put(LambdaUtil.getFieldName(ForumPostDto::getType), type);
        }

        if (topicId != null) {
            request.put(LambdaUtil.getFieldName(ForumPostDto::getTopics), new Long[]{topicId});
        }

        if (StringUtils.isNotBlank(queryContent)) {
            request.put(LambdaUtil.getFieldName(ForumPostDto::getContent), queryContent);
        }

        if (StringUtils.isNotBlank(mobile)) {
            MobileUserDto mobileUserDto = mobileUserService.selectByMobile(mobile);
            if (mobileUserDto == null) {
                return Response.<Page<ForumPostDto>>ok().wrap(Page.empty(request.getPageNo(), request.getPageSize()));
            } else {
                request.put(LambdaUtil.getFieldName(ForumPostDto::getAuthorId), mobileUserDto.getId());
            }
        }

        if (StringUtils.isNotBlank(startTime)) {
            request.put(ForumConstants.PUBLISH_TIME_SLOT_KEY_PAIR.getLeft(), startTime);
        }
        if (StringUtils.isNotBlank(endTime)) {
            request.put(ForumConstants.PUBLISH_TIME_SLOT_KEY_PAIR.getRight(), endTime);
        }

        if (StringUtils.isNotBlank(mobile)) {
            MobileUserDto mobileUserDto = mobileUserService.selectByMobile(mobile);
            if (mobileUserDto == null) {
                return Response.<Page<ForumPostDto>>ok().wrap(Page.empty(request.getPageNo(), request.getPageSize()));
            } else {
                request.put(LambdaUtil.getFieldName(ForumPostDto::getAuthorId), mobileUserDto.getId());
            }
        }

        //未删除的帖子
        request.put(LambdaUtil.getFieldName(ForumPostDto::getDeletedFlag), SystemConstants.NO);
        long current = System.currentTimeMillis();
        int toatl = forumPostService.queryTotal(request.getParams());
        long current2 = System.currentTimeMillis();
        List<ForumPostDto> forumPostDtos = null;
        if (toatl > 0) {
            forumPostDtos = forumPostService.queryList(request.getParams());
            forumPostDtos.forEach(forumPostDto -> {
                VillageDto villageDto = villageService.selectCacheById(forumPostDto.getVillageId());
                if (villageDto != null) {
                    forumPostDto.setVillageName(villageDto.getName());
                }
            });
            long current3 = System.currentTimeMillis();
        } else {
            forumPostDtos = new ArrayList<>();
        }

        Page<ForumPostDto> page = new Page<>(request.getPageNo(), request.getPageSize(), toatl, forumPostDtos);
        return Response.<Page<ForumPostDto>>ok().wrap(page);
    }


    /**
     * 帖子列表
     *
     * @param
     * @return
     */

    @GetMapping("list")
    @Operation(summary = "帖子列表查询")
    @RequirePermissions(values = "forumPost:list")
    public Response<Page<ForumPostDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "类别,默认没有类别") @RequestParam(required = false) Byte type,
            @Parameter(description = "话题Id") @RequestParam(required = false) Long topicId,
            @Parameter(description = "查询content") @RequestParam(required = false) String queryContent
    ) {
        Request request = Request.configParams(Request.parseParams(httpServletRequest));


        if (type != null) {
            request.put(LambdaUtil.getFieldName(ForumPostDto::getType), type);
        }

        if (topicId != null) {
            request.put(LambdaUtil.getFieldName(ForumPostDto::getTopics), new Long[]{topicId});
        }

        if (StringUtils.isNotBlank(queryContent)) {
            request.put(LambdaUtil.getFieldName(ForumPostDto::getContent), queryContent);
        }

        //未删除的帖子
        request.put(LambdaUtil.getFieldName(ForumPostDto::getDeletedFlag), SystemConstants.NO);
        //置顶帖子
        request.put(LambdaUtil.getFieldName(ForumPostDto::getTopFlag), SystemConstants.YES);

        int toatl = forumPostService.queryTotal(request.getParams());
        List<ForumPostDto> forumPostDtos = null;
        if (toatl > 0) {
            forumPostDtos = forumPostService.queryList(request.getParams());
        } else {
            forumPostDtos = new ArrayList<>();
        }

        Page<ForumPostDto> page = new Page<>(request.getPageNo(), request.getPageSize(), toatl, forumPostDtos);
        return Response.<Page<ForumPostDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "forumPost:edit")
    @Operation(summary = "在编辑时根据id查询发帖管理详情")
    public Response<ForumPostDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (forumPostService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        ForumPostDto forumPostDto = forumPostService.selectById(id);
        VillageDto villageDto = villageService.selectCacheById(forumPostDto.getVillageId());
        if (villageDto != null) {
            forumPostDto.setVillageName(villageDto.getName());
        }

        return Response.<ForumPostDto>ok().wrap(forumPostDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "forumPost:info")
    @Operation(summary = "根据id查询发帖管理的详情")
    public Response<ForumPostDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (forumPostService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        ForumPostDto forumPostDto = forumPostService.selectById(id);
        VillageDto villageDto = villageService.selectCacheById(forumPostDto.getVillageId());
        if (villageDto != null) {
            forumPostDto.setVillageName(villageDto.getName());
        }

        return Response.<ForumPostDto>ok().wrap(forumPostDto);
    }

    /**
     * 保存
     *
     * @param forumPostDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "forumPost:edit")
    @Operation(summary = "新增发帖管理")
    public Response<Object> save(@RequestBody @Validated ForumPostDto forumPostDto) {

        //填充基础数据
        fillSaveCommonData(forumPostDto);

        forumPostDto.setTenantId(SessionHolder.getSysUser().getTenantId());

        VillageDto villageDto = villageService.selectCacheById(forumPostDto.getVillageId());
        if (villageDto == null) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        forumPostDto.setCityCode(villageDto.getCityCode());
        forumPostDto.setTopFlag(SystemConstants.YES);

        ValidatorContext validatorContext = new ValidatorContext();
        validatorContext.setTenantId(SessionHolder.getSysUser().getTenantId());
        validatorContext.setVillageId(forumPostDto.getVillageId());
        validatorContext.setText(forumPostDto.getContent());
        validatorContext.setImgUrls(forumPostDto.getImageUrls());

        Response validate = validatorChain.validate(validatorContext);
        if (!validate.isSuccess()) {
            return Response.error(validate.getMessage());
        }
        //因为是系统管理员 所以移动端的id不存在,标记为-1
        forumPostDto.setAuthorId(Long.valueOf(SystemConstants.NONEXISTENT_ID));
        forumPostDto.setVisibleFlag(SystemConstants.NO);
        forumPostDto.setPublishTime(new Date());
        forumPostDto.setTopFlag(SystemConstants.YES);

        forumPostService.post(forumPostDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param forumPostDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "forumPost:edit")
    @Operation(summary = "根据id修改发帖管理")
    public Response<Object> update(@RequestBody @Validated ForumPostDto forumPostDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(forumPostDto.getId()));
        if (forumPostService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(forumPostDto);

        ValidatorContext validatorContext = new ValidatorContext();
        validatorContext.setTenantId(SessionHolder.getSysUser().getTenantId());
        validatorContext.setVillageId(forumPostDto.getVillageId());
        validatorContext.setText(forumPostDto.getContent());
        validatorContext.setImgUrls(forumPostDto.getImageUrls());

        Response validate = validatorChain.validate(validatorContext);
        if (!validate.isSuccess()) {
            return Response.error(validate.getMessage());
        }
        forumPostDto.setEditTime(new Date());

        forumPostService.updateById(forumPostDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param forumAuditReq
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "forumPost:delete")
    @Operation(summary = "根据多条记录id批量删除发帖管理")
    public Response<Object> delete(@RequestBody ForumAuditReq forumAuditReq) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : forumAuditReq.getIds()) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (forumPostService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }

        }

        LoginUserSession sysUser = SessionHolder.getSysUser();
        forumPostService.auditDeleteBatch(sysUser.getTenantId(), sysUser.getUserId(), forumAuditReq.getViolationTypes(), forumAuditReq.getRemark(), forumAuditReq.getIds());


        List<String> violationTypeStringList = new ArrayList<>(forumAuditReq.getViolationTypes().size());
        for (Byte violationType : forumAuditReq.getViolationTypes()) {
            String s = SysCodeUtils.easyToGetName(SysCodeKeyConstants.FORUM_VIOLATION_TYPE, String.valueOf(violationType));
            violationTypeStringList.add(s);
        }

        //通知用户删除消息
        for (Long id : forumAuditReq.getIds()) {
            ForumPostDto forumPostDto = forumPostService.selectById(id);
            MobileUserDto mobileUserDto = mobileUserService.selectCacheById(forumPostDto.getAuthorId());

            if (mobileUserDto != null) {
                mobileUserMsgBusiness.pushMsg(
                        sysUser.getTenantId(),
                        forumPostDto.getVillageId(),
                        Collections.singletonList(mobileUserDto),
                        MobileUserMsgConstants.SourceType.FORUM_MSG,
                        forumPostDto.getId(),
                        MobileUserMsgConstants.SourceType.FORUM_MSG.getDefaultTitle(),
                        "您在\"" + DateUtils.format(forumPostDto.getPublishTime(), DateUtils.FormatType.COMMON) + "\"发布的帖子因涉及" + JacksonUtils.toJsonString(violationTypeStringList) + "被管理员删除",
                        true,
                        new PushConstants.PushType[]{PushConstants.PushType.WECHAT_OFFICIAL}
                );
            }
        }

        return Response.ok();
    }
}
